import { Notification, BrowserWindow } from "electron";
import { join } from "node:path";
import { existsSync } from "node:fs";
import { exec } from "node:child_process";
import { release } from "node:os";

interface ElectronNotificationOptions {
  title?: string;
  body: string;
  icon?: string;
  silent?: boolean;
  subtitle?: string; // Mac特有
  sound?: string; // Mac特有
  hasReply?: boolean;
  timeoutType?: "default" | "never";
  urgency?: "low" | "normal" | "critical";
}

export interface SystemNotificationOptions {
  title?: string;
  message: string;
  route?: string;
  sound?: string;
  messageId?: number;
  recipientId?: number;
  targetId?: number | string;
  targetType?: string;
}

class NotificationManager {
  private win: BrowserWindow | null = null;
  private isMac = process.platform === "darwin";
  private isWindows7 =
    process.platform === "win32" && release().startsWith("6.1");

  constructor(win: BrowserWindow | null) {
    this.win = win;
  }

  setMainWindow(win: BrowserWindow) {
    this.win = win;
  }

  private async requestNotificationPermission(): Promise<boolean> {
    // 简化权限检查逻辑，Electron的通知权限通常由系统自动处理
    return Notification.isSupported();
  }

  private playSound(soundPath: string) {
    if (!this.win) return;

    if (soundPath.startsWith("http")) {
      this.win.webContents.send("play-sound", soundPath);
    } else if (existsSync(soundPath)) {
      // 在Mac上可以使用afplay播放本地声音文件
      if (this.isMac) {
        exec(`afplay "${soundPath}"`, (error) => {
          if (error) {
            console.error("播放声音失败:", error);
          }
        });
      } else {
        this.win.webContents.send("play-sound", soundPath);
      }
    }
  }

  // Windows 7 使用替代方案显示通知
  private showWindows7Notification(
    options: SystemNotificationOptions
  ) {
    const {
      message,
      title,
      route,
      sound,
      messageId,
      recipientId,
      targetId,
      targetType
    } = options;

    const body =
      typeof message === "string" && message.trim().length > 0
        ? message
        : "您有一条新的通知";

    // 对于 Windows 7，通过 IPC 发送通知信息到渲染进程
    // 让渲染进程通过 HTML5 Notification API 显示通知
    if (this.win) {
      this.win.webContents.send("show-html5-notification", {
        title: title || "PureAdmin",
        body,
        route,
        sound,
        messageId,
        recipientId,
        targetId,
        targetType
      });

      // 播放声音
      if (sound) {
        this.playSound(sound);
      }

      return { success: true };
    }

    return { success: false, error: "No window available" };
  }

  async showNotification(options: SystemNotificationOptions) {
    const {
      message,
      title,
      route,
      sound,
      messageId,
      recipientId,
      targetId,
      targetType
    } = options;

    const body = message || "您有一条新的通知";
    const notificationTitle = title || "PureAdmin";

    // Windows 7 使用特殊的处理方式
    if (this.isWindows7) {
      return this.showWindows7Notification({
        ...options,
        message: body,
        title: notificationTitle
      });
    }

    try {
      if (!Notification.isSupported()) {
        // 如果系统不支持通知，回退到 Windows 7 方案
        return this.showWindows7Notification({
          ...options,
          message: body,
          title: notificationTitle
        });
      }

      const notificationOptions: ElectronNotificationOptions = {
        title: notificationTitle,
        body,
        icon: join(process.env.PUBLIC!, "favicon.ico"),
        hasReply: false,
        timeoutType: "default",
        urgency: "normal",
        silent: true // 默认静音，避免重复播放声音
      };

      // Mac特有设置
      if (this.isMac) {
        if (sound) {
          // 如果是本地声音文件且存在，直接使用系统通知声音
          if (!sound.startsWith("http") && existsSync(sound)) {
            notificationOptions.sound = sound;
          } else {
            // 否则播放声音并保持通知静音
            this.playSound(sound);
            notificationOptions.silent = true;
          }
        }
      } else {
        // 非Mac平台手动播放声音
        if (sound) {
          this.playSound(sound);
        }
      }

      const notification = new Notification(notificationOptions);

      notification.on("click", () => {
        if (this.win) {
          this.win.show();
          this.win.focus();

          if (route) {
            this.win.webContents.send("navigate-to-route", route);
          }

          this.win.webContents.send("notification-clicked", {
            title: notificationTitle,
            message: body,
            route,
            sound,
            messageId,
            recipientId,
            targetId,
            targetType
          });
        }
      });

      notification.show();
      return { success: true };
    } catch (error: any) {
      console.error("显示通知失败:", error);
      // 出错时回退到 Windows 7 方案
      return this.showWindows7Notification({
        ...options,
        message: body,
        title: notificationTitle
      });
    }
  }
}

export default NotificationManager;
